/*
 *
 *  Created by John David Duncan on 2/20/09.
 *  Copyright 2009 Sun Microsystems. All rights reserved.
 *
 */

/*
 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; version 2 of the License.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
*/

#include <stdlib.h>
#include <errno.h>
#include "Scanner.h"
#include "utilities.h"

// like coco_string_crate_char(), but remove quotes

char *unquote(wchar_t *value) {  
  int len = coco_string_length(value) - 1;
  char *res = new char[len];
  
  char *rpos = res;
  for (int i = 1; i < len; ++i) 
    *rpos++ = (char) value[i]; 
  *rpos = 0;
  return res;
}


bool token_to_int(unsigned int *lvalue, wchar_t *token) {
  unsigned int i = strtoul(coco_string_create_char(token), 
                           (char **) NULL, 10);
  if((i == 0) || (i == ULONG_MAX))
    if((errno == EINVAL) || (errno == ERANGE)) 
      return false;
  
  *lvalue = i;
  return true;
}


char *unescape_string(char *str) {
  /* The unescaped string will never be longer than the original */
  char *res = (char *) malloc(strlen(str) + 1);
  char *c = res;
  
  while(*str) {
    if(*str == '\\') {
      switch(*(str+1)) {
        case 'n':
          *c++ = '\n';
          break;
        case 'r':
          *c++ = '\r';
          break;
        case 't':
          *c++ = '\t';
          break;
        case '\\':
          *c++ = '\\';
          break;
        case '\'':
          *c++ = '\'';
          break;
      }
      str+=2;
    }
    else    
      *c++ = *str++;
  }
  *c = 0;
  return res;
}
